<template>
  <div class="video-content">
    <div class="video-card">
      <div class="upload-video">
        <el-upload
          class="m-upload"
          drag
          ref="upload"
          accept="video/*"
          action="/"
          :before-upload="beforeUpload"
          :http-request="customHttpQeq"
          :show-file-list="false"
          v-if="!formParams.videoUrl"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">点击上传或将文件拖入此区域</div>
          <div class="el-upload__tip" slot="tip">
            推荐尺寸：16:9、18:9、21:9 的横版视频 推荐分辨率：≥ 1920*1080
            <el-progress :percentage="videoProgress" style="padding: 10px 48px 0" v-if="videoProgress != 0 && videoProgress != 100"></el-progress>
          </div>
        </el-upload>
        <div id="mse" class="video-mse"></div>
        <el-divider><i class="el-icon-apple"></i></el-divider>
        <el-form label-width="140px" style="margin-top:42px">
          <el-form-item label="标题" required>
            <el-input size="medium" maxlength="30" show-word-limit placeholder="请输入 5 ~ 30 个字符" v-model="formParams.title"></el-input>
          </el-form-item>
          <el-form-item label="封面" required>
            <div class="article-cover-add" @click="selectImgVisible = true">
              <i class="el-icon-plus" v-if="!formParams.videoImgUrl"></i>
              <div class="template" @mouseover="oneBannerMouseover" @mouseleave="oneBannerMouseleave" v-else>
                <img class="article-cover-img" :src="formParams.videoImgUrl" alt="" />
                <i class="article-cover-delete el-icon-circle-close" @click.stop="deleteSelectOneImg" v-if="oneBannerSelectFlag"></i>
              </div>
            </div>
            <p style="font-size:12px;color:#999;line-height:28px">清晰美观的封面有利于推荐，建议分辨率不低于 1920*1080（大小不超过 20M）建议的封面</p>
          </el-form-item>
          <el-form-item label="视频简介">
            <el-input size="medium" type="textarea" autosize maxlength="400" placeholder="请输入视频简介" v-model="formParams.videoIntro"></el-input>
          </el-form-item>
          <el-form-item label="创作类型" prop="writeType">
            <el-radio-group v-model="formParams.writeType">
              <el-radio label="原创"></el-radio>
              <el-radio label="转载"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="创作收益" prop="delivery">
            <p class="original-tips">
              发布原创视频可获得收益，非原创内容勾选原创将受到处罚，详见
              <el-link type="primary" href="https://doc.toutiao.com/detail/181/149/150?enter_from=publish" target="_blank"> 查看详情</el-link>
            </p>
          </el-form-item>
        </el-form>
        <div class="bottom-fix">
          <div class="publish-footer-content">
            <div class="go-back">
              <router-link to="/"><el-button size="small" icon="el-icon-back" circle></el-button></router-link>
            </div>
            <div class="footer-btn">
              <el-button size="small" @click="previewDrawer">预览</el-button>
              <el-button size="small" :disabled="postId != ''" @click="selectPushTime">定时发布</el-button>
              <el-button size="small" type="danger" :loading="btnLoading" @click="submitPublish(1)">发布</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-drawer :visible.sync="drawer" :with-header="false" size="28%">
      <div class="m-drawer">
        <div class="phone-review">
          <div class="review-bg"></div>
          <div class="rewiew-component">
            <p>{{ formParams.title }}</p>
            <img :src="formParams.videoImgUrl" alt="" />
            <span class="backgrounk-video"></span>
          </div>
        </div>
      </div>
    </el-drawer>
    <!-- 选择图片 -->
    <select-img :selectImgVisible="selectImgVisible" @closeVisible="selectImgVisible = false" @select-recommend-img="selectRecommendImg" />
    <!-- 定时发送时间选择 -->
    <select-time :selectTimeVisible="selectTimeVisible" :loading="timeLoading" @handleClose="selectTimeVisible = false" @submit="timingPublish" />
  </div>
</template>

<script>
import { createPost, queryPostDetail, createSchedulePost, updatePost } from '../api';
import SelectImg from '../select-img';
import SelectTime from '../select-time';
import { mapGetters } from 'vuex';
import OSS from 'ali-oss';
import Player from 'xgplayer';

export default {
  components: { SelectImg, SelectTime },
  data() {
    return {
      selectImgVisible: false, // 选择封面图
      oneBannerSelectFlag: false,
      btnLoading: false,
      selectTimeVisible: false, // 定时发布
      timeLoading: false,
      formParams: {
        videoUrl: '',
        title: '',
        videoImgUrl: '',
        videoIntro: '',
        writeType: '原创'
      },
      drawer: false,
      videoProgress: 0
    };
  },
  computed: {
    ...mapGetters(['userId']),
    postId() {
      return this.$route.query.postId || '';
    }
  },
  created() {
    if (this.postId) {
      queryPostDetail({ postId: this.postId }).then(res => {
        if (res.success) {
          new Player({
            id: 'mse',
            url: res.data.videoUrl,
            poster: res.data.coverImg[0]
          });
          this.dealData(res.data);
        }
      });
    }
  },
  methods: {
    timingPublish(data) {
      this.timeLoading = true;
      this.submitPublish(2, data);
    },
    selectPushTime() {
      if (this.checkParams()) {
        this.selectTimeVisible = true;
      }
    },
    dealData(data) {
      this.formParams.videoUrl = data.videoUrl;
      this.formParams.title = data.title;
      this.formParams.videoImgUrl = data.coverImg[0];
      this.formParams.videoIntro = data.content;
    },
    submitPublish(idx, scheduleTime) {
      if (this.checkParams()) {
        const params = {
          title: this.formParams.title,
          content: this.formParams.videoIntro,
          postType: 2,
          coverSize: 1,
          userId: this.userId,
          coverUrlList: [this.formParams.videoImgUrl],
          videoUrl: this.formParams.videoUrl
        };
        if (idx == 1) {
          this.btnLoading = true;
          if (this.postId) {
            // 更新帖子
            updatePost(params, { url: `/admin/updatePost/${this.postId}` }).then(res => {
              this.btnLoading = false;
              if (res.success) {
                this.$message({
                  message: '帖子更新成功',
                  type: 'success'
                });
                this.$router.push('/');
              }
            });
          } else {
            createPost(params).then(res => {
              this.btnLoading = false;
              if (res.success) {
                this.$message({
                  message: '帖子发布成功',
                  type: 'success'
                });
                this.$router.push('/');
              }
            });
          }
        }
        if (idx == 2) {
          params.scheduleTime = scheduleTime;
          createSchedulePost(params).then(res => {
            this.selectTimeVisible = false;
            this.timeLoading = false;
            if (res.success) {
              this.$message({
                message: '帖子将在指定时间发布',
                type: 'success'
              });
              this.$router.push('/');
            }
          });
        }
      }
    },
    checkParams() {
      if (!this.formParams.videoUrl) {
        this.$message.error('请上传视频');
        return false;
      }
      if (!this.formParams.title || this.formParams.title.trim() == '') {
        this.$message.error('请输入视频标题');
        return false;
      }
      if (this.formParams.title.length < 5) {
        this.$message.error('视频标题长度不小于5字符');
        return false;
      }
      if (!this.formParams.videoImgUrl) {
        this.$message.error('请上传视频封面');
        return false;
      }
      return true;
    },
    previewDrawer() {
      if (this.checkParams()) {
        this.drawer = true;
      }
    },
    selectRecommendImg(data) {
      this.formParams.videoImgUrl = data;
      this.selectImgVisible = false;
    },
    oneBannerMouseover() {
      this.oneBannerSelectFlag = true;
    },
    oneBannerMouseleave() {
      this.oneBannerSelectFlag = false;
    },
    deleteSelectOneImg() {
      this.oneBannerSelectFlag = false;
      this.formParams.videoImgUrl = '';
    },
    beforeUpload(file, list) {
      let type = file.type;
      if (!type.includes('video')) {
        this.$message.error('只能上传视频文件');
        return false;
      }
      return true;
    },
    async customHttpQeq(e) {
      let _this = this;
      let ossConfig = {
        bucket: 'mokr',
        region: 'oss-cn-hangzhou',
        accessKeyId: 'LTAI4GKtWVVqqeaoByh4iQxY',
        accessKeySecret: 'klsV5Emf7YBNT3Iz4Btas2LUm0YUct'
      };
      let client = new OSS(ossConfig);
      let data = e.file;
      try {
        let result = await client.multipartUpload(`uploadVideo/${data.name}`, data, {
          progress: function(p, checkpoint) {
            // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
            _this.videoProgress = Number.parseInt(p * 100, 10);
            console.log(_this.videoProgress);
          },
          mime: 'video/mp4'
        });
        console.log(result.res);
        _this.formParams.videoUrl = result.res.requestUrls[0].split('?')[0];
        new Player({
          id: 'mse',
          url: _this.formParams.videoUrl
        });
      } catch (e) {
        console.error(e);
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style lang="scss">
html {
  background: #fafafa;
}
.video-content {
  position: relative;
  min-height: 100vh;
  background: #fafafa;
  .video-card {
    width: 750px;
    background: #fff;
    margin: 30px auto;
    background-color: #fff;
    .upload-video {
      padding: 52px;
      min-height: 558px;
      .m-upload {
        text-align: center;
        margin-bottom: 60px;
      }
      .video-mse {
        margin: 0 auto;
      }
    }
    .original-tips {
      font-size: 14px;
      color: #555;
      height: 20px;
      line-height: 20px;
      margin-top: 10px;
    }
    .article-cover-add {
      position: relative;
      display: inline-block;
      width: 120px;
      height: 85px;
      line-height: 85px;
      margin-right: 12px;
      vertical-align: top;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      border: 1px dashed #d8d8d8;
      background-color: #fafafa;
      .template {
        height: 100%;
        .article-cover-img {
          width: 100%;
          height: 100%;
          border-radius: 3px;
          object-fit: cover;
        }
        .article-cover-delete {
          position: absolute;
          right: -8px;
          top: -8px;
        }
      }
    }
    .bottom-fix {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 54px;
      line-height: 54px;
      z-index: 100002;
      background-color: #fff;
      text-align: right;
      border-top: 1px solid #e8e8e8;
      .publish-footer-content {
        height: 100%;
        width: 750px;
        margin: 0 auto;
        .go-back {
          float: left;
          width: 120px;
          text-align: left;
        }
        .footer-btn {
          float: right;
        }
      }
    }
  }
}
.m-drawer {
  display: flex;
  justify-content: center;
  .phone-review {
    position: relative;
    width: 280px;
    height: 567px;
    padding-top: 20px;
    text-align: left;
    .review-bg {
      height: 100%;
      width: 280px;
      background: url('http://sf1-ttcdn-tos.pstatp.com/obj/mp/preview_feed.png') no-repeat;
      background-size: contain;
    }
    .rewiew-component {
      position: absolute;
      top: 120px;
      left: 28px;
      width: 225px;
      height: 358px;
      padding: 6px 12px 0;
      background: #fff;
      p {
        line-height: 16px;
        font-size: 13px;
        color: #333;
      }
      img {
        width: 100%;
        height: 124px;
        border-radius: 3px;
        object-fit: cover;
        margin-top: 6px;
      }
      .backgrounk-video {
        display: block;
        position: absolute;
        left: 0;
        top: -160px;
        bottom: 0;
        right: 0;
        background: url(https://mokr.oss-cn-hangzhou.aliyuncs.com/custom/playicon_video.png) no-repeat center center;
        background-size: 32px;
      }
    }
  }
}

.el-form-item {
  margin-bottom: 36px;
}
</style>
